package cn.yinzhiping.interceptorlearn.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Handler;

/**
 * @author yinzhiping
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtil tokenUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行前。。。");
        String token = request.getHeader("Authorization");
        System.out.println(token+"22");
        if(StringUtils.isEmpty(token)){
            System.out.println("false-----");
            return false;
        }
        boolean flag = tokenUtil.checkToken(token);
        if(false==flag){
            JSONObject outputMSg = new JSONObject();
            outputMSg.put("code", 403);
            outputMSg.put("content", "");
            outputMSg.put("msg", "没有权限");
            output(outputMSg, request, response);
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器执行后。。。");
    }
    public void output(Object json, HttpServletRequest request, HttpServletResponse response) throws IOException, IOException {
        //String header = request.getHeader("Origin");
        response.setContentType("application/json;charset=UTF-8;");
        PrintWriter out = response.getWriter();
        out.println(json);
        out.flush();
        out.close();
    }
}
